-module(tr_listener).
-behaviour(gen_server).

-export([start_link/1]).

-export([init/1,
         handle_cast/2,
         terminate/2]).

-record(state, {listen_sock,conn_count=0}).

start_link(Port) ->
    gen_server:start_link({local, ?MODULE}, ?MODULE, [Port], []).

init([Port]) ->
    {ok, LSock} = gen_tcp:listen(Port, [{active, once}]),
    
    %% 进入监听状态
    gen_server:cast(self(), {listen, LSock}),
    {ok, #state{listen_sock=LSock}}.

handle_cast({listen, LSock}, #state{conn_count=Count}) ->

    {ok, Socket} = gen_tcp:accept(LSock),
    
    %% 启动接收者进程，并把Socket控制权转交给接收者进程
    %%{ok, Acceptor} = tr_acceptor_sup:start_child(Socket),
    {ok, Acceptor} = tr_listener_sup:start_child(Socket),
    gen_tcp:controlling_process(Socket, Acceptor),

    %% 重新进入监听状态
    gen_server:cast(self(), {listen, LSock}),

    {noreply, #state{conn_count=Count+1}}.

terminate(_Reason, _State) ->
    ok.



